package com.lw.leetcode.other.a;

/**
 * Created with IntelliJ IDEA.
 * 1360. 日期之间隔几天
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/23 22:26
 */
public class DaysBetweenDates {

    private int[][] months = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
            {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
    private int[] days = {365, 366};

    public int daysBetweenDates(String date1, String date2) {
        String[] d1 = date1.split("-");
        String[] d2 = date2.split("-");
        int year1 = Integer.valueOf(d1[0]), year2 = Integer.valueOf(d2[0]);
        int month1 = Integer.valueOf(d1[1]), month2 = Integer.valueOf(d2[1]);
        int day1 = Integer.valueOf(d1[2]), day2 = Integer.valueOf(d2[2]);
        int s1 = gap(year1, month1, day1);
        int s2 = gap(year2, month2, day2);
        return Math.abs(s1 - s2);
    }

    public int gap(int year, int month, int day) {
        int sum = 0;
        int flag = isleapyear(year);
        for (int i = 1971; i < year; i++) {
            sum += days[isleapyear(i)];
        }
        for (int i = 1; i < month; i++) {
            sum += months[flag][i];
        }
        sum += day;
        return sum;
    }

    public int isleapyear(int year) {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            return 1;
        }
        return 0;
    }

}
